<?php

/**
 * Created by PhpStorm.
 * User: yutongfu
 * Date: 2019/7/6
 * Time: 12:51 PM
 */
class MessageClass
{
    //三私一公
    private static $instance;
    private static $server;
    public $MessageHandler;

    private function __construct()
    {
        //创建websocket对象
        self::$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
        //注册事件
        self::$server->on('open', [$this, 'onOpen']);//绑定onOpen方法
        self::$server->on('message', [$this, 'onMessage']);
        self::$server->on('WorkerStart', [$this, 'onWorkerStart']);
        self::$server->on('close', [$this, 'onClose']);
        //启动
        //self::$server->start();改成通过方法调用
    }

    //公有的静态方法
    public static function getInstance()
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new MessageClass();
        }
        return self::$instance;
    }

    //创建onOpen方法
    function onOpen($server)
    {
        echo "连接上了";
    }

    function onMessage($server, $frame)
    {
        //self::$server->reload();//每次更改代码都需要重启服务器，在这里reload让其调用workerStart，重新加载代码
        echo "马上要执行message事件了";
        var_dump($frame);
        //根据传入参数调用处理事件的类，参数包含执行的方法,例如： {"cmd":"login","data":"123456"}
        $data = json_decode($frame->data, true);
        var_dump($this->MessageHandler);
        if (method_exists($this->MessageHandler, $data['cmd'])) {
            echo 22;
            call_user_func([$this->MessageHandler, $data['cmd']], $data);//调用方法
        }
    }

    //此方法是服务器连接的时候就会执行
    public function onWorkerStart($server)
    {
        echo "onWorkerStart....";
        include "./MessageHandler.php";
        $this->MessageHandler = new MessageHandler();
    }

    function onClose($server, $fd)
    {

    }

    //启动
    public function start()
    {
        self::$server->start();
    }
}

MessageClass::getInstance()->start();